/**
 * 2010-2011 xiha.org
 */
package org.xiha.wiki.apps.tools;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.xiha.wiki.database.AckView;
import org.xiha.wiki.database.BasicDatabase;
import org.xiha.wiki.domain.Ack;

import com.sleepycat.collections.StoredSortedMap;

/**
 * @author summer
 * 
 */
public class SubjectTool {
    private List<String>       subjects      = null;
    private static SubjectTool subjectTool   = new SubjectTool();
    private static Date        lastDate;
    private final static int   EXPIRE_MINUTE = 10;
    
    public SubjectTool() {
        subjects = null;
        BasicDatabase db = new BasicDatabase("~/");
        db.openAck();
        
        AckView basicView = new AckView(db);
        
        StoredSortedMap<String, Ack> acks = basicView.getAckStoredMap();
        if (subjects == null) {
            subjects = new ArrayList<String>();
            for (String key : acks.keySet()) {
                subjects.add(acks.get(key).getSubject());
            }
        }
        db.closeAck();
        lastDate = new Date();
    }
    
    public static SubjectTool getInstance() {
        synchronized (lastDate) {
            Calendar cl1 = Calendar.getInstance();
            cl1.setTime(lastDate);
            cl1.add(Calendar.MINUTE, EXPIRE_MINUTE);
            Calendar cl2 = Calendar.getInstance();
            cl2.setTime(new Date());
            if (cl1.compareTo(cl2) < 0) {
                subjectTool = new SubjectTool();
            }
        }
        return subjectTool;
    }
    
    public final List<String> getSubjects() {
        return subjects;
    }
    
}
